package cn.golxen.blog.filter;

import cn.golxen.blog.commons.utils.JWTUtils;
import cn.golxen.blog.exception.exceptionClass.GetTokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
public class BlogFilter implements Filter {

//    String checkUri;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("过滤器初始化执行");
//        this.checkUri=filterConfig.getInitParameter("checkUri");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("执行过滤器");
//        log.info(checkUri);

        HttpServletRequest request= (HttpServletRequest) servletRequest;
//        HttpServletResponse response=(HttpServletResponse) servletResponse;



        if (!request.getMethod().equals("OPTIONS")){
            String token=request.getHeader("blog-token");
            log.info(request.getMethod());
            log.info(request.getHeader("blog-token"));
            if (token==null||token.isEmpty())
                throw new GetTokenException();

            //验证token正确性
            if (JWTUtils.verifyJWT(token)){
                //验证token是否过期
                if (!JWTUtils.isExpires(token))
                    filterChain.doFilter(servletRequest,servletResponse);
            }
        }else{
            log.info(request.getMethod());
            log.info(request.getHeader("blog-token"));
            filterChain.doFilter(servletRequest,servletResponse);
        }


    }
    @Override
    public void destroy() {
        Filter.super.destroy();
        log.info("过滤器销毁执行");
    }
}
